<template>
  <el-drawer
    title="标签数据批量导入"
    size="60%"
    :visible.sync="drawerVisible"
    direction="rtl"
    :close-on-press-escape="false"
    :wrapperClosable="false"
    :destroy-on-close="true"
    :before-close="beforeClose"
    custom-class="tag-drawer batch-drawer register-manual-drawer"
    v-drawerResize
  >
    <div class="tag-import">
      <tag-step :step="step" :active="config.stepNumber"></tag-step>
      <div class="drawer-wrap">
        <div class="drawer-content tag-scrollbar">
          <div v-if="config.stepNumber === 0" class="upload-page">
            <el-row>
              <el-col :span="24" align="center">
                <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="90px">
                  <el-form-item prop="identifyTagId" label="唯一标识">
                    <el-select v-model="editForm.identifyTagId">
                      <el-option label="---" value=""></el-option>
                      <el-option
                        v-for="item in idList"
                        :key="item.tagId"
                        :label="item.tagNm"
                        :value="item.tagId"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
            <tag-upload
              ref="fileUpload"
              drag
              :fileList="upload.fileList"
              @uploadFun="fileFun"
              @removeFun="fileRemove"
              :fileLimit="upload.fileLimit"
            >
              <template #tip>
                只能上传对应的模板文件，一次导入只能上传一个文件
              </template>
            </tag-upload>
          </div>
          <div v-if="config.stepNumber === 1" class="table-page">
            <tag-content-header search setting @toolFun="toolFun" :settingData="columns">
              <template #title>
                <span v-if="config.stepNumber === 1"
                  >附件共有<span class="data-count data-normal">{{ sourceData.recordNumber }}</span
                  >条记录数，初步导入成功<span class="data-count data-success">{{ sourceData.successNumber }}</span
                  >条，导入失败<span class="data-count data-faild">{{ sourceData.failNumber }}</span
                  >条，导入成功率<span class="data-count data-success">{{ sourceData.successRate }}</span
                  >，点击“完成”确定导入</span
                >
              </template>
            </tag-content-header>
            <tag-table
              ref="table"
              @refresh="getList"
              :data="dataList"
              :loading="loading"
              :columns="columns"
              :params="params"
              :total="totalSize"
            >
            </tag-table>
          </div>
        </div>
      </div>
    </div>

    <div class="drawer-btns">
      <el-button size="medium" @click="beforeClose()">取消</el-button>
      <el-button type="primary" size="medium" v-if="config.stepNumber === 0" @click="handleDownload">
        模板下载
      </el-button>
      <el-button type="primary" size="medium" v-else @click="reset">重新上传</el-button>
      <el-button type="primary" @click="back" v-if="config.stepNumber === 1">上一步</el-button>
      <el-button type="primary" size="medium" @click="next" v-if="!config.error">
        {{ config.stepNumber === 1 ? '完成' : '下一步' }}
      </el-button>
    </div>
  </el-drawer>
</template>

<script>
export default {
  data() {
    return {
      drawerVisible: false,
      loading: false,
      step: [
        {
          icon: 'iconUpload',
          name: '上传数据'
        },
        {
          icon: 'iconPreview',
          name: '预览数据'
        }
      ],
      tagId: '',
      editForm: {
        identifyTagId: ''
      },
      editFormRules: {
        identifyTagId: [{ required: true, message: '唯一标识不能为空', trigger: 'change' }]
      },
      idList: [],
      dataList: [],
      columns: [],
      params: {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      },
      totalSize: 0,
      upload: {
        fileId: '',
        fileList: [],
        fileLimit: {
          type: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          typeMsg: '只能上传excel文件'
        }
      },
      config: {
        stepNumber: 0,
        error: false
      },
      sourceData: {
        plfmId: '',
        dbNm: '',
        tableNm: '',
        recordNumber: '',
        successNumber: '',
        failNumber: '',
        successRate: ''
      }
    }
  },
  methods: {
    showDrawer(tagId) {
      this.tagId = tagId
      this.getIdList()
      this.drawerVisible = true
    },
    getIdList() {
      this.$ajax({
        url: this.$ajax.setUrl('ast/astData/import/allIdentifierTag'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.idList = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    fileFun(params) {
      this.upload.fileId = params.fileId
      this.upload.fileList = params.fileList.slice(-1)
    },
    fileRemove() {
      this.upload.fileId = ''
    },
    reset() {
      this.loading = false
      this.editForm.identifyTagId = ''
      this.idList = []
      this.dataList = []
      this.columns = []
      this.params = {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      }
      this.totalSize = 0
      this.upload.fileId = ''
      this.upload.fileList = []
      this.sourceData = {
        plfmId: '',
        dbNm: '',
        tableNm: '',
        recordNumber: '',
        successNumber: '',
        failNumber: '',
        successRate: ''
      }
      if (this.config.stepNumber === 0) this.$refs.editForm.clearValidate()
      this.config = {
        stepNumber: 0,
        error: false
      }
    },
    toolFun(operation) {
      switch (operation) {
        case 'search':
          // 搜索动作
          this.$refs['table'].searchToggle()
          break
        case 'refresh':
          // 刷新动作
          this.getList()
          break
      }
    },
    getPreviewList() {
      this.params.currentPageNum = 1
      this.loading = true
      this.$ajax({
        url: this.$ajax.setUrl('ast/astData/import/excel'),
        method: 'post',
        data: this.$ajax.setData({
          fileId: this.upload.fileId,
          tagId: this.tagId,
          identifyTagId: this.editForm.identifyTagId
        })
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.sourceData.plfmId = data.data.plfmId
          this.sourceData.dbNm = data.data.dbNm
          this.sourceData.tableNm = data.data.tableNm
          this.sourceData.recordNumber = data.data.recordNumber
          this.sourceData.successNumber = data.data.successNumber
          this.sourceData.failNumber = data.data.failNumber
          this.sourceData.successRate = data.data.successRate
          this.getList()
        } else {
          this.$message.error(data.data || data.msg)
          this.config.error = true
        }
        this.loading = false
      })
    },
    getList() {
      this.loading = true
      this.$ajax({
        url: this.$ajax.setUrl('ast/astData/import/records'),
        method: 'get',
        params: this.$ajax.setParams(Object.assign({}, this.params, { tagId: this.tagId }))
      }).then(({ data }) => {
        if (data && data.code === '0') {
          if (data.data.currentPageNum === this.params.currentPageNum) {
            this.setColumns(data.data.columnNames)
            this.dataList = data.data.records
            this.totalSize = data.data.totalSize
          }
        } else {
          this.$message.error(data.data || data.msg)
        }
        this.loading = false
      })
    },
    setColumns(data) {
      if (this.columns.length !== data.length) {
        let columns = []
        data.forEach(item => {
          let param = {
            show: true,
            label: item.columnCname,
            prop: item.columnEname,
            search: true,
            searchKey: '',
            align: 'center'
          }
          if (item.columnEname === 'dqc_error') {
            param.searchType = 'select'
            param.searchList = [{ key: '通过', value: '通过' }, { key: '不通过', value: '不通过' }]
          }
          columns.push(param)
        })
        this.columns = columns
      }
    },
    next() {
      if (this.loading) {
        this.$alert('请等待加载完成')
        return
      }
      let step = this.config.stepNumber
      if (step === 0) {
        this.$refs.editForm.validate()
        if (!this.editForm.identifyTagId) return
        if (!this.upload.fileId) {
          this.$alert('请先上传需要导入的文件')
          return
        }
      }
      switch (step) {
        case 0:
          this.config.stepNumber = step + 1
          this.getPreviewList()
          break
        case 1:
          this.$emit('callback', this.sourceData)
          this.reset()
          this.drawerVisible = false
          break
      }
    },
    back() {
      this.config.stepNumber = 0
    },
    beforeClose() {
      var close = true
      var msg = ''
      if (this.config.stepNumber > 0) {
        close = false
        msg = '确定要取消导入吗？'
      }
      if (close) {
        this.reset()
        this.drawerVisible = false
        this.$emit('callback')
      } else {
        this.$confirm(msg)
          .then(() => {
            this.reset()
            this.drawerVisible = false
            this.$emit('callback')
          })
          .catch(() => {})
      }
    },
    handleDownload() {
      this.$ajax({
        url: this.$ajax.setUrl('ast/astData/import/tmpl'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.$dlFile(data.data)
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    close() {
      this.reset()
      this.drawerVisible = false
      this.$emit('callback')
    }
  }
}
</script>

<style lang="scss">
.tag-drawer.register-manual-drawer {
  .el-drawer__body {
    .drawer-wrap {
      top: 100px;
      &.disabled {
        bottom: 0;
      }
    }
  }
  .el-form {
    width: 360px;
  }
}
</style>
